package com.htdz.controller;

import com.github.pagehelper.PageInfo;
import com.htdz.entity.*;
import com.htdz.service.RoleService;
import com.htdz.service.UsersService;
import com.htdz.util.CommonRedisUtil;
import com.htdz.util.JsonUtil;
import com.htdz.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/users")
public class UsersController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	public UsersService usersService;
	@Autowired
	public RedisUtil redisUtil;
	@Autowired
	public RoleService roleService;


	/**
	 * 列出所有用户
	 * @param model
	 * @param pageNum 第几页
	 * @return
	 */
	@RequestMapping(value = "/listUsers")
	public String listUsers(HttpServletRequest request, Model model, Integer pageNum){
		if( pageNum == null ) pageNum = 1;
        Users users = new Users();
        List<Users> usersList = usersService.listUsers(users,pageNum);
        model.addAttribute("usersList",usersList);
        model.addAttribute("pageInfo",new PageInfo(usersList));
		return "listUsers";
	}
	
	//新增
	@RequestMapping(value = "/saveUsers")
	public String saveUsers(Users users){
	    users.setPwd("888888");
	    users.setStatus(1);
	    users.setEnabled(1);
        usersService.saveUsers(users);
		return "redirect:/users/listUsers";
	}

	@RequestMapping("/deleteUsers")
	public String deleteUsers(HttpServletRequest request,Model model,Long usersId){
        usersService.delete(usersId);
		return "redirect:/users/listUsers";
	}

    @RequestMapping("/linkAddUsers")
    public String linkAddUsers(HttpServletRequest request,Model model){
        return "addUsers";
    }

    /**
     * 检测用户名是否存在
     * @param usersName
     * @return
     */
    @RequestMapping(value="/checkUsersName",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkUsersName(String usersName){
        Map map = new HashMap();
        Integer retVal = usersService.checkUsersName(usersName);
        if(retVal == 0){
            map.put("valid",true);
        }else{
            map.put("valid",false);
        }
        return JsonUtil.obj2json(map);
    }
}
